import time
import logging

import memcache


class ValueCacher(object):
  def __init__(self, expire_sec):
    self.timestamp = None
    self.value = None
    self.expire_sec = expire_sec

  def update(self, value, timestamp=None):
    if timestamp is None:
      timestamp = time.time()
    self.timestamp = timestamp
    self.value = value
    return value

  def get(self, timestamp=None):
    if timestamp is None:
      timestamp = time.time()
    if self.timestamp is not None and (timestamp - self.timestamp) < self.expire_sec:
      return self.value
    else:
      return None


class ValueMemCacher(object):
  def __init__(self, expire_sec, memcached_key, mc: memcache.Client):
    self.mc = mc
    self.expire_sec = expire_sec
    self.key = memcached_key

  def update(self, value, timestamp=None):
    res = self.mc.set(self.key, value, time=self.expire_sec)
    if not res:
      logging.debug("Memcached set value failed.")
    return res

  def get(self, timestamp=None):
    fetched_result = self.mc.get(self.key)
    return fetched_result
